-- tcpClient.lua 

TCPserver_ip = "192.168.3.168"
TCPserver_port = 777
UDPserver_ip = "47.106.78.44"
UDPserver_port = 8989
System_led = 4
gpio.mode(System_led, gpio.OUTPUT)

msg = {}
am2301 = {}
msg["device_name"] = "device_test"
msg["device_num"] = 1
msg["device_addr"] = 1

function receive_msg(str)
    print(str)
end

function send_msg(sck)
    --tcp_client:send("hello word "..send_count.."\r\n")
    status,temp,humi,temp_dec,humi_dec = dht.read(5)
    if status==dht.OK then
        am2301["temp"] = temp
        am2301["humi"] = humi
        msg["data_val"] = am2301
        ok,json = pcall(cjson.encode, msg)
        if ok then
            gpio.write(System_led, gpio.LOW)
            print("send json file to socket server")
            sck:send(json)
            gpio.write(System_led, gpio.HIGH)
        else
            print("failed to encode json")
        end
    end
end

if tcp_client==nil then
    print("connect tcp_client")
    tcp_client = net.createConnection(net.TCP, 1)
    tcp_client:on("disconnection", function(sck, c) 
        print("tcp_client disconnection")  
        tcp_client:close() 
        tcp_client=nil 
    end)
    tcp_client:on("reconnection", function(sck, c) print("tcp_client reconnection") send_msg(sck) end)
    tcp_client:on("connection", function(sck, c) print("tcp_client connection") send_msg(sck) end)
    tcp_client:on("receive", function(sck, c) print("tcp_client receive") receive_msg(c) end)
    tcp_client:connect(TCPserver_port, TCPserver_ip)
else
    print("tcp_client send message")
    send_msg(tcp_client)
end

if udp_client==nil then
    print("connect udp_client")
    udp_client = net.createConnection(net.UDP, 1)
    udp_client:on("receive", function(sck, c) print("udp_client receive") receive_msg(c) end)
    udp_client:connect(UDPserver_port, UDPserver_ip)
else
    print("udp_client send message")
    send_msg(udp_client)
end

